import classNames from 'classnames';
import { useEffect, useRef } from 'react';
import styles from './index.module.scss';

interface TextAreaProps
  extends React.DetailedHTMLProps<
    React.TextareaHTMLAttributes<HTMLTextAreaElement>,
    HTMLTextAreaElement
  > {
  value: string;
}

export default function Textarea(props: TextAreaProps) {
  const {
    className,
    maxLength = 100,
    value,
    autoFocus = true,
    ...rest
  } = props;

  const TextareaRef = useRef<HTMLTextAreaElement>(null);
  useEffect(() => {
    TextareaRef.current?.setSelectionRange(-1, -1);
  }, []);

  return (
    <div className={styles.root}>
      {/* 文本输入框 */}
      <textarea
        className={classNames('textarea', className)}
        {...rest}
        value={value}
        ref={TextareaRef}
        autoFocus={autoFocus}
        maxLength={maxLength}
      />
      {/* 当前字数/最大允许字数 */}
      <div className="count">
        {value.length}/{maxLength}
      </div>
    </div>
  );
}
